package edu.sctu.yueding.alipay;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alipay.sdk.app.PayTask;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import edu.sctu.yueding.R;
import edu.sctu.yueding.activitys.BaseActivity;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.MetaBean;
import edu.sctu.yueding.bean.PayOrderBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.Constants;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.L;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.CustomDialog;


/**
 * 重要说明:
 * <p/>
 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
 */
public class PayActivity extends BaseActivity implements View.OnClickListener {

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2016082301790747";

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088421644261341";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "KKKKK";

    private ProgressUtil progressUtil;

    private ProgressDialog progressDialog;

    /**
     * 商户私钥，pkcs8格式
     */
    public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJ" +
            "cAgEAAoGBALDNUH16bz8SwvLwbgYnPmayJr1HUQhBX+yP8KzVxXmJ3NSkff5k86KG5yVYdHIsc" +
            "6G/aLnLo47vqmZ7Y095cpu0Swe4fiV1weKCJDHNiI9QrhMk72PShTWSgrbA6T4K8FI5geTxHbD" +
            "WIHcRF/xi6hwXojkeS2fwTsb6t/c9kTGRAgMBAAECgYBm0bAqmOZTVvTa1aoWmAH5NUfEMdJVK" +
            "7e+WmNMEDH8oYk0fMjtBgaOEUghdtSZhXJlsWwVCPGAca62VLGHiYh1PrjIII0sOdcgqDkmeMRp" +
            "EQ3w9KMNuQ23w7+rSareZrA4nIKZ5uPuYlqvvN2ovVNRqizblxmoeVscSXrsmwSTcQJBAOIAFR9" +
            "lfcyFPBdp6IhuCeywHrhMBCX7OxE+mwBSUPKPdg7HC+cLGRR4QxpKvDknFIQcAvBKpm4qk9uEug" +
            "n9tz0CQQDIRWFgicucE4GDF09nKmaeFFXXiX3AW4To234xRUur9Qup59diOdZt/cMHl10lgnlNjs" +
            "+Q/pbWBIntPRlOkejlAkB9ppgX1aCklir7xYlgWPWxn5Xk13ay+0Qy6UDaY+nXgkWcH7SRZ00xY" +
            "U/FjWmqyPySGtTTbl2sAIYmVVvt9B7tAkA2uV6mdoDAoUPeglwcIKXxxDTAtL079sYWqwOMixbm" +
            "YgtR3hwopw1E+PZ1+JJnUYO8Aa4OPMMSsCLQRMXJhm1RAkEAwSgvC7dikvAx8B7WcEKRQRRQ+wh1" +
            "qi7ddNtTqiDsr9YPP46OVK5ogRwodYswntSRExc01gmGceOIJCHlJFng1A==";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;


    private String orderString;
    private long orderId;

    private TextView hostName;
    private TextView goodsDetails;
    private TextView price;
    private TextView count;
    private TextView totalMoney;
    private ImageView back;
    private LinearLayout layout;
    private Button payButton;

    private IWXAPI api;

    private RadioGroup radioGroup;
    private RadioButton pay;

    HashMap<String, String> map;
    String token;

    String matchId;
    long routeId;
    long teamId;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        sendSuccessMessageToServer();
                        finishDialog();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };

    /**
     * 支付成功通知后台
     */
    private void sendSuccessMessageToServer() {

        GetVolleyHttp.getInstance(this).getStringGETJsonData(URLConfig.URL_PAY_SUCCESS(orderId), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(response);
                MetaBean meta = jsonObject.getObject("meta", MetaBean.class);
                int code = meta.getCode();

                if (code == 200) {
                    L.d("paysuccess", "200");
                } else {
                    L.d("paysuccess", "not 200");
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();

            }
        }, "");


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment_order_information);
        initViews();
        initSystemBar(this, 0);
        initOrderData();
    }

    private void initViews() {

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        api.registerApp(Constants.APP_ID);
        progressUtil = ProgressUtil.getInstance(this, "");

        hostName = (TextView) findViewById(R.id.pay_order_host_name);
        goodsDetails = (TextView) findViewById(R.id.pay_order_goods_details_text);
        price = (TextView) findViewById(R.id.pay_order_price);
        count = (TextView) findViewById(R.id.pay_order_count);
        totalMoney = (TextView) findViewById(R.id.pay_order_total_money);
        layout = (LinearLayout) findViewById(R.id.pay_order_pay_method_layout);
        back = (ImageView) findViewById(R.id.pay_order_back);

        radioGroup = (RadioGroup) findViewById(R.id.pay_radiogroup);
        pay = (RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());


        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                // 点击事件获取的选择对象
                pay = (RadioButton) radioGroup
                        .findViewById(checkedId);

//                Toast.makeText(getApplicationContext(),
//                        "获取的ID是" + pay.getText(),
//                        Toast.LENGTH_LONG).show();
            }
        });

        payButton = (Button) findViewById(R.id.pay_order_button);

        payButton.setOnClickListener(this);
        back.setOnClickListener(this);

        layout.setOnClickListener(this);

        map = new HashMap<>();
        SharePreference sharePreference;
        sharePreference = SharePreference.getInstance(this);

        Intent intent = getIntent();
        boolean payAgain = intent.getBooleanExtra("payAgain", false);

        if (payAgain) {

            matchId = String.valueOf(intent.getLongExtra("matchId", 0l));
            teamId = intent.getLongExtra("teamId", 0l);
            routeId = intent.getLongExtra("routeId", 0l);

        } else {

            matchId = sharePreference.getString(CacheConfig.CACHE_MATCH_ID);
            routeId = sharePreference.getLong(CacheConfig.CACHE_ROUTE_ID);
            teamId = sharePreference.getInt(CacheConfig.CACHE_TEAM_ID);
        }

        map.put("matchId", String.valueOf(matchId));
        map.put("routeId", String.valueOf(routeId));
        map.put("teamId", String.valueOf(teamId));
        token = sharePreference.getString(CacheConfig.CACHE_TOKEN);

        initOrderData();
    }

    private void wxpay() {

//        payButton.setEnabled(false);

        GetVolleyHttp.getInstance(this).getStringGETJsonData(URLConfig.getMyWxPay(orderId), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                progressUtil.dismiss(progressDialog);


//                JsonBaseBeen<PayRequestBean> paybean = JSON.parseObject(response, new TypeReference<JsonBaseBeen<PayRequestBean>>() {
//                }.getType());

                Log.e("---", response);
                Log.e("orderId", String.valueOf(orderId));

                JSONObject j = JSON.parseObject(response).getJSONObject("data");

                try {
                    PayReq req = new PayReq();
                    //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                    req.appId = j.getString("appId");
                    req.partnerId = j.getString("partnerId");
                    req.prepayId = j.getString("prepayId");
                    req.nonceStr = j.getString("nonceStr");
                    req.timeStamp = j.getString("timestamp");
                    req.packageValue = j.getString("packageName");
                    req.sign = j.getString("sign");
                    req.extData = "app data"; // optional
                    Toast.makeText(PayActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信

                    boolean r = api.sendReq(req);
                    Toast.makeText(PayActivity.this, String.valueOf(r), Toast.LENGTH_SHORT).show();

                } catch (Exception e) {
                    Log.e("PAY_GET", "异常：" + e.getMessage());
                    Toast.makeText(PayActivity.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }

//                payButton.setEnabled(true);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {


            }
        }, "");


    }


    private void pay() {

        GetVolleyHttp.getInstance(this).getStringGETJsonData(URLConfig.getMyAlipay(orderId), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.e("alipay", response);

                JSONObject json = JSON.parseObject(response);

                JSONObject m = json.getJSONObject("meta");

                if (Integer.parseInt(m.getString("code")) == 200) {

                    orderString = json.getString("data");

                }

                progressUtil.dismiss(progressDialog);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressUtil.dismiss(progressDialog);

            }
        }, "");


    }

    private void initOrderData() {

        GetVolleyHttp.getInstance(this).getStringPOSTJsonData(URLConfig.URL_PAY_ORDER, map, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {


                Log.e("ss",response);

                JsonBaseBeen<PayOrderBean> orderBean = JSON.parseObject(response, new TypeReference<JsonBaseBeen<PayOrderBean>>() {
                }.getType());

                PayOrderBean orderInfo = orderBean.getData();

                orderId = orderInfo.getId();
                hostName.setText("主办方：" + orderInfo.getSponsor());
                goodsDetails.setText(orderInfo.getOrderName());


                //保留两位小数
                DecimalFormat decimalFormat = new DecimalFormat("0.00");

                double priceNum = orderInfo.getPrice();
                int countNum = orderInfo.getCount();

                price.setText(decimalFormat.format(priceNum) + "");
                count.setText(countNum + "");

                double totalMon = orderInfo.getTotalAmount();
                totalMoney.setText("￥" + decimalFormat.format(totalMon) + "");


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }, URLConfig.BEAREAR + token);
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pay_order_back:
//                JumpUtils.jumpActivity(this, SignUpMyTeamActivity.class);
                finish();
                break;

            case R.id.pay_order_button:

                progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL, false);

                if (pay.getText().equals("1")) {
                    pay();
                    payV2(v);

                } else if (pay.getText().equals("2")) {
                    wxpay();
                }


            default:
                break;
        }
    }

    /**
     * 支付宝支付业务
     *
     * @param v
     */
    public void payV2(View v) {
        if (TextUtils.isEmpty(APPID) || TextUtils.isEmpty(RSA_PRIVATE)) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        /**
         * orderInfo的获取必须来自服务端；
         */
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);

                if (orderString == null) {
                    Log.d("orderString", "is null ...");
                } else {
                    Log.d("orderString", orderString);

                    Map<String, String> result = alipay.payV2(orderString, true);
                    Log.i("msp", result.toString());

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public void finishDialog() {

        final CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessage("提示：支付结果，可通过个人中心查看！");
        builder.setPositiveButton("立即查看", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
//                JumpUtils.jumpActivity(PayActivity.this, MyOrderListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("flag", 3);
                JumpUtils.activityToFragmentJump(PayActivity.this, bundle);

//                SharePreference.getInstance(PayActivity.this).removeOneCache(CacheConfig.CACHE_LINE_NUMBER);


                SharePreference.getInstance(PayActivity.this).removeOneCache(CacheConfig.CACHE_LINE_MIN_NUMBER);
                SharePreference.getInstance(PayActivity.this).removeOneCache(CacheConfig.CACHE_LINE_MAX_NUMBER);


                finish();
            }
        });
        builder.create().show();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
//            JumpUtils.jumpActivity(this, SignUpMyTeamActivity.class);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
